#include "ui_manager.h"
#include "../app/main_app.h"
#include "function_button_manager.h"
#include "../database/sqlite_manager.h"
#include "../config/cabrillo_config.h"
#include "cabrillo_config_dialog.h"
#include "../database/cty_dat_parser.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <sstream>
#include <gtk/gtk.h>

// 初始化静态成员
GtkBuilder* UIManager::current_builder = nullptr;

GtkBuilder* UIManager::create_builder() {
    GtkBuilder *builder = gtk_builder_new();
    
    // Load UI file directly from the UI directory relative to the executable
    char* exec_path = g_file_read_link("/proc/self/exe", NULL);
    char* ui_path = nullptr;
    
    if (exec_path) {
        char* exec_dir = g_path_get_dirname(exec_path);
        ui_path = g_build_filename(exec_dir, "UI", "main.glade", NULL);
        g_free(exec_dir);
        g_free(exec_path);
    }
    
    GError *error = nullptr;
    bool ui_loaded = false;
    if (ui_path) {
        if (gtk_builder_add_from_file(builder, ui_path, &error)) {
            ui_loaded = true;
        } else {
            g_clear_error(&error);
        }
        g_free(ui_path);
    }
    
    if (!ui_loaded) {
        return nullptr;
    }
    
    return builder;
}

GtkWidget* UIManager::get_main_window(GtkBuilder *builder) {
    GtkWidget *window = GTK_WIDGET(gtk_builder_get_object(builder, "main_window"));
    return window;
}

void UIManager::apply_css_styles(GtkBuilder *builder, GtkWidget *window) {
    GtkCssProvider *css_provider = GTK_CSS_PROVIDER(gtk_builder_get_object(builder, "css_provider"));
    if (css_provider) {
        GtkStyleContext *context = gtk_widget_get_style_context(window);
        gtk_style_context_add_provider(context, GTK_STYLE_PROVIDER(css_provider), GTK_STYLE_PROVIDER_PRIORITY_USER);
    }
}

void UIManager::connect_signals(GtkBuilder *builder) {
    // 保存builder对象供信号处理函数使用
    set_builder(builder);
    gtk_builder_connect_signals(builder, nullptr);
    
    // 获取输入框控件
    GtkWidget *callsign_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edCallSign"));
    GtkWidget *snt_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edSnt"));
    GtkWidget *rcv_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edRcv"));
    GtkWidget *name_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edName"));
    GtkWidget *memo_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edMemo"));
    
    // 连接edCallSign的按键事件和内容变化事件
    if (callsign_entry) {
        g_signal_connect(callsign_entry, "key-press-event", G_CALLBACK(on_callsign_key_press), builder);
        g_signal_connect(callsign_entry, "changed", G_CALLBACK(on_callsign_changed), NULL);
        //增加一个callsign focus out 事件
        g_signal_connect(callsign_entry, "focus-out-event", G_CALLBACK(on_callsign_focus_out), builder);
    }
    
    // 连接edSnt的焦点进入事件和按键事件
    if (snt_entry) {
        g_signal_connect(snt_entry, "focus-in-event", G_CALLBACK(on_snt_focus_in), builder);
        g_signal_connect(snt_entry, "key-press-event", G_CALLBACK(on_snt_key_press), builder);
    }
    
    // 连接edRcv的焦点进入事件和按键事件
    if (rcv_entry) {
        g_signal_connect(rcv_entry, "focus-in-event", G_CALLBACK(on_rcv_focus_in), builder);
        g_signal_connect(rcv_entry, "key-press-event", G_CALLBACK(on_rcv_key_press), builder);
    }
    
    // 连接edName的按键事件
    if (name_entry) {
        g_signal_connect(name_entry, "key-press-event", G_CALLBACK(on_name_key_press), builder);
    }
    
    // 连接edMemo的按键事件
    if (memo_entry) {
        g_signal_connect(memo_entry, "key-press-event", G_CALLBACK(on_memo_key_press), builder);
    }
    
    // 连接edSendJust的按键事件
    GtkWidget *sendjust_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edSendJust"));
    if (sendjust_entry) {
        g_signal_connect(sendjust_entry, "key-press-event", G_CALLBACK(on_sendjust_key_press), builder);
    }
    
    // 连接cw_cabrillo_button的点击事件
    GtkWidget *cabrillo_button = GTK_WIDGET(gtk_builder_get_object(builder, "cw_cabrillo_button"));
    if (cabrillo_button) {
        g_signal_connect(cabrillo_button, "clicked", G_CALLBACK(on_cw_cabrillo_button_clicked), nullptr);
    }
    
    // 连接export_cabrillo_button的点击事件
    GtkWidget *export_cabrillo_button = GTK_WIDGET(gtk_builder_get_object(builder, "export_cabrillo_button"));
    if (export_cabrillo_button) {
        g_signal_connect(export_cabrillo_button, "clicked", G_CALLBACK(on_export_cabrillo_button_clicked), nullptr);
    }
    
    // 连接export_ADI_button的点击事件
    GtkWidget *export_ADI_button = GTK_WIDGET(gtk_builder_get_object(builder, "export_ADI_button"));
    if (export_ADI_button) {
        g_signal_connect(export_ADI_button, "clicked", G_CALLBACK(on_export_ADI_button_clicked), nullptr);
    }
    
    
}

// 新增：设置当前builder对象
void UIManager::set_builder(GtkBuilder* builder) {
    current_builder = builder;
}

// 新增：获取当前builder对象
GtkBuilder* UIManager::get_builder() {
    return current_builder;
}

// 新增：频率输入框内容改变的回调函数
G_MODULE_EXPORT void on_frequency_changed(GtkWidget *entry, gpointer data) {
    // 注意：为了更好的用户体验，我们可能不希望在每次按键时都保存配置
    // 可以考虑只在失去焦点或按下回车键时保存
    std::cout << "频率值已更改: " << gtk_entry_get_text(GTK_ENTRY(entry)) << std::endl;
}

// 新增：WPM下拉框选择改变的回调函数
G_MODULE_EXPORT void on_wpm_changed(GtkWidget *combo, gpointer data) {
    // 通过UIManager获取保存的builder对象
    GtkBuilder *builder = UIManager::get_builder();
    if (builder) {
        GtkWidget *frequency_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edFrequency"));
        GtkWidget *wpm_combo = GTK_WIDGET(gtk_builder_get_object(builder, "cmbWpm"));
        
        // 保存配置到文件
        MainApp::save_frequency_wpm_config(frequency_entry, wpm_combo);
    }
}

// 新增：频率输入框失去焦点的回调函数
G_MODULE_EXPORT gboolean on_frequency_focus_out(GtkWidget *entry, GdkEvent *event, gpointer data) {
    // 通过UIManager获取保存的builder对象
    GtkBuilder *builder = UIManager::get_builder();
    if (builder) {
        GtkWidget *frequency_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edFrequency"));
        GtkWidget *wpm_combo = GTK_WIDGET(gtk_builder_get_object(builder, "cmbWpm"));
        
        // 保存配置到文件
        MainApp::save_frequency_wpm_config(frequency_entry, wpm_combo);
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

// 新增：频率输入框按下回车键的回调函数
G_MODULE_EXPORT gboolean on_frequency_key_press(GtkWidget *entry, GdkEventKey *event, gpointer data) {
    if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter) {
        // 通过UIManager获取保存的builder对象
        GtkBuilder *builder = UIManager::get_builder();
        if (builder) {
            GtkWidget *frequency_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edFrequency"));
            GtkWidget *wpm_combo = GTK_WIDGET(gtk_builder_get_object(builder, "cmbWpm"));
            
            // 保存配置到文件
            MainApp::save_frequency_wpm_config(frequency_entry, wpm_combo);
        }
        
        return GDK_EVENT_STOP; // 停止传播事件
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

std::string UIManager::get_ui_path() {
    char* exec_path = g_file_read_link("/proc/self/exe", NULL);
    char* ui_path = nullptr;
    std::string result = "";
    
    if (exec_path) {
        char* exec_dir = g_path_get_dirname(exec_path);
        ui_path = g_build_filename(exec_dir, "UI", "main.glade", NULL);
        if (ui_path) {
            result = std::string(ui_path);
        }
        g_free(exec_dir);
        g_free(exec_path);
        g_free(ui_path);
    }
    
    return result;
}

// 新增：edCallSign输入框按下按键的回调函数
G_MODULE_EXPORT gboolean on_callsign_key_press(GtkWidget *entry, GdkEventKey *event, gpointer data) {
    if (event->keyval == GDK_KEY_space) {
        // 通过UIManager获取保存的builder对象
        GtkBuilder *builder = UIManager::get_builder();
        if (builder) {
            // 焦点转移到edSnt输入框
            GtkWidget *snt_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edSnt"));
            if (snt_entry) {
                gtk_widget_grab_focus(snt_entry);
            }
        }
        
        return GDK_EVENT_STOP; // 停止传播事件
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

// 新增：edCallSign输入框内容变化的回调函数
G_MODULE_EXPORT void on_callsign_changed(GtkWidget *entry, gpointer data) {
    // 获取edCallSign输入框的内容
    const gchar* callsignText = gtk_entry_get_text(GTK_ENTRY(entry));
    if (callsignText && strlen(callsignText) > 0) {
        // 获取LogGridDialog实例
        LogGridDialog* logGridDialog = MainApp::getLogWindowInstance();
        if (MainApp::isLogWindowCreated() && logGridDialog) {
            // 使用callsignText作为前缀筛选数据
            std::string callsignPrefix(callsignText);
            logGridDialog->populate_log_data(callsignPrefix);
        }
    } else {
        LogGridDialog* logGridDialog = MainApp::getLogWindowInstance();
        if (MainApp::isLogWindowCreated() && logGridDialog) {
            // 清空log_grid_dialog中的数据
            logGridDialog->populate_log_data();
        }
    }
    
}

G_MODULE_EXPORT gboolean on_callsign_focus_out(GtkWidget *entry, GdkEvent *event, gpointer data) {
    // 获取UI builder以访问其他控件
    GtkBuilder *builder = UIManager::get_builder();
    if (builder) {
        const gchar* callsignText = gtk_entry_get_text(GTK_ENTRY(entry));
        // 检查呼号是否为空
        if (callsignText && strlen(callsignText) > 0) {
            std::string callsignUpper(callsignText);
            // 转换为大写
            std::transform(callsignUpper.begin(), callsignUpper.end(), callsignUpper.begin(), ::toupper);
            // 查询国家信息
            const auto* info = MainApp::parser.lookupCountry(callsignUpper.c_str());
            if (info) {
                std::cout << "Country: " << info->country_name << ", CQ Zone: " << info->cq_zone << std::endl;
                std::string countryInfo = info->country_name + " (CQ:" + std::to_string(info->cq_zone) +",ITU:" 
                        + std::to_string(info->itu_zone) +",PREFIX:"+ info->primary_prefix 
                        +",LAT:"+ std::to_string(info->latitude) 
                        +",LON:"+ std::to_string(info->longitude) + ")";
                // 获取edQSOMemo控件
                GtkWidget *infoLabel = GTK_WIDGET(gtk_builder_get_object(builder, "infoLabel"));
                if (infoLabel) {
                    // 设置infoLabel的文本
                    gtk_label_set_text(GTK_LABEL(infoLabel), countryInfo.c_str());
                } else {
                    std::cerr << "infoLabel控件不存在" << std::endl;
                }
            } else {
                std::cout << "未找到呼号 " << callsignUpper << " 对应的国家信息" << std::endl;
            }
        }
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}
// 新增：edSnt输入框获得焦点的回调函数
G_MODULE_EXPORT gboolean on_snt_focus_in(GtkWidget *entry, GdkEvent *event, gpointer data) {
    // 通过UIManager获取保存的builder对象
    GtkBuilder *builder = UIManager::get_builder();
    if (builder) {
        // 如果edSnt内容为空，则填充为599
        const gchar* text = gtk_entry_get_text(GTK_ENTRY(entry));
        if (text && strlen(text) == 0) {
            gtk_entry_set_text(GTK_ENTRY(entry), "599");
        }
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

// 新增：edSnt输入框按下按键的回调函数
G_MODULE_EXPORT gboolean on_snt_key_press(GtkWidget *entry, GdkEventKey *event, gpointer data) {
    if (event->keyval == GDK_KEY_space) {
        // 通过UIManager获取保存的builder对象
        GtkBuilder *builder = UIManager::get_builder();
        if (builder) {
            // 焦点转移到edRcv输入框
            GtkWidget *rcv_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edRcv"));
            if (rcv_entry) {
                gtk_widget_grab_focus(rcv_entry);
            }
        }
        
        return GDK_EVENT_STOP; // 停止传播事件
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

// 新增：edRcv输入框获得焦点的回调函数
G_MODULE_EXPORT gboolean on_rcv_focus_in(GtkWidget *entry, GdkEvent *event, gpointer data) {
    // 通过UIManager获取保存的builder对象
    GtkBuilder *builder = UIManager::get_builder();
    if (builder) {
        // 如果edRcv内容为空，则填充为599
        const gchar* text = gtk_entry_get_text(GTK_ENTRY(entry));
        if (text && strlen(text) == 0) {
            gtk_entry_set_text(GTK_ENTRY(entry), "599");
        }
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

// 新增：edRcv输入框按下按键的回调函数
G_MODULE_EXPORT gboolean on_rcv_key_press(GtkWidget *entry, GdkEventKey *event, gpointer data) {
    if (event->keyval == GDK_KEY_space) {
        // 通过UIManager获取保存的builder对象
        GtkBuilder *builder = UIManager::get_builder();
        if (builder) {
            // 焦点转移到edName输入框
            GtkWidget *name_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edName"));
            if (name_entry) {
                gtk_widget_grab_focus(name_entry);
            }
        }
        
        return GDK_EVENT_STOP; // 停止传播事件
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

// 新增：edName输入框按下按键的回调函数
G_MODULE_EXPORT gboolean on_name_key_press(GtkWidget *entry, GdkEventKey *event, gpointer data) {
    if (event->keyval == GDK_KEY_space) {
        // 通过UIManager获取保存的builder对象
        GtkBuilder *builder = UIManager::get_builder();
        if (builder) {
            // 焦点转移到edMemo输入框
            GtkWidget *memo_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edMemo"));
            if (memo_entry) {
                gtk_widget_grab_focus(memo_entry);
            }
        }
        
        return GDK_EVENT_STOP; // 停止传播事件
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

// 新增：edMemo输入框按下按键的回调函数
G_MODULE_EXPORT gboolean on_memo_key_press(GtkWidget *entry, GdkEventKey *event, gpointer data) {
    if (event->keyval == GDK_KEY_space) {
        // 通过UIManager获取保存的builder对象
        GtkBuilder *builder = UIManager::get_builder();
        if (builder) {
            // 焦点转移到edCallSign输入框
            GtkWidget *callsign_entry = GTK_WIDGET(gtk_builder_get_object(builder, "edCallSign"));
            if (callsign_entry) {
                gtk_widget_grab_focus(callsign_entry);
            }
        }
        
        return GDK_EVENT_STOP; // 停止传播事件
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

// 新增：edSendJust输入框按下回车键的回调函数
G_MODULE_EXPORT gboolean on_sendjust_key_press(GtkWidget *entry, GdkEventKey *event, gpointer data) {
    if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_KP_Enter) {
        // 通过UIManager获取保存的builder对象
        GtkBuilder *builder = UIManager::get_builder();
        if (builder) {
            // 获取edSendJust的内容
            const gchar* text = gtk_entry_get_text(GTK_ENTRY(entry));
            if (text && strlen(text) > 0) {
                // 调用FunctionButtonManager::sendCW发送内容
                std::string cwText(text);
                FunctionButtonManager::sendCW(builder, cwText);
            }
        }
        
        return GDK_EVENT_STOP; // 停止传播事件
    }
    
    return GDK_EVENT_PROPAGATE; // 继续传播事件
}

extern "C" void on_export_cabrillo_button_clicked(GtkWidget* widget, gpointer data) {
    std::cout << "导出Cabrillo日志按钮被点击" << std::endl;
    
    // 创建文件保存对话框
    GtkWidget *dialog = gtk_file_chooser_dialog_new("保存Cabrillo日志文件",
                                                    nullptr,
                                                    GTK_FILE_CHOOSER_ACTION_SAVE,
                                                    "_取消", GTK_RESPONSE_CANCEL,
                                                    "_保存", GTK_RESPONSE_ACCEPT,
                                                    nullptr);
    std::string filename;
    CabrilloConfig* cabrilloConfig = CabrilloConfig::getInstance();
    filename = cabrilloConfig->get("CabrilloConfig.CALLSIGN") + ".log";
    // 设置默认文件名
    gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), filename.c_str());
    
    // 设置文件过滤器
    GtkFileFilter *filter = gtk_file_filter_new();
    gtk_file_filter_set_name(filter, "Cabrillo Files (*.log)");
    gtk_file_filter_add_pattern(filter, "*.log");
    gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter);
    
    // 显示对话框
    gint res = gtk_dialog_run(GTK_DIALOG(dialog));
    
    if (res == GTK_RESPONSE_ACCEPT) {
        char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
        std::cout << "选择的文件名: " << filename << std::endl;
        
        // 导出Cabrillo日志
        if (UIManager::export_cabrillo_log(filename)) {
            // 显示成功消息
            GtkWidget *msg_dialog = gtk_message_dialog_new(nullptr,
                                                           GTK_DIALOG_MODAL,
                                                           GTK_MESSAGE_INFO,
                                                           GTK_BUTTONS_OK,
                                                           "Cabrillo日志导出成功！");
            gtk_dialog_run(GTK_DIALOG(msg_dialog));
            gtk_widget_destroy(msg_dialog);
        } else {
            // 显示错误消息
            GtkWidget *msg_dialog = gtk_message_dialog_new(nullptr,
                                                           GTK_DIALOG_MODAL,
                                                           GTK_MESSAGE_ERROR,
                                                           GTK_BUTTONS_OK,
                                                           "Cabrillo日志导出失败！");
            gtk_dialog_run(GTK_DIALOG(msg_dialog));
            gtk_widget_destroy(msg_dialog);
        }
        
        g_free(filename);
    }
    
    gtk_widget_destroy(dialog);
}

// Cabrillo日志导出函数实现
bool UIManager::export_cabrillo_log(const std::string& filename) {
    std::cout << "开始导出Cabrillo日志到文件: " << filename << std::endl;
    
    try {
        // 获取数据库管理器实例
        SQLiteManager& dbManager = SQLiteManager::getInstance();
        
        // 获取所有QSO记录
        std::vector<QSORecord> records = dbManager.getAllQSOs();
        
        // 获取Cabrillo配置
        CabrilloConfig* cabrilloConfig = CabrilloConfig::getInstance();
        
        // 创建并打开输出文件
        std::ofstream outFile(filename);
        if (!outFile.is_open()) {
            std::cerr << "无法创建或打开文件: " << filename << std::endl;
            return false;
        }
        
        // 写入Cabrillo文件头部信息
        outFile << "START-OF-LOG: 3.0\n";
        outFile << "CREATED-BY: sHamLogX11\n";
        
        // 写入基本配置信息
        if (cabrilloConfig->hasKey("CabrilloConfig.CALLSIGN")) {
            outFile << "CALLSIGN: " << cabrilloConfig->get("CabrilloConfig.CALLSIGN") << "\n";
        }
        
        if (cabrilloConfig->hasKey("CabrilloConfig.CONTEST")) {
            outFile << "CONTEST: " << cabrilloConfig->get("CabrilloConfig.CONTEST") << "\n";
        }
        
        // 写入其他可选配置信息
        std::vector<std::string> configKeys = {
            "CabrilloConfig.OPERATORS", "CabrilloConfig.CLUB", "CabrilloConfig.LOCATION",
            "CabrilloConfig.CATEGORY-OPERATOR", "CabrilloConfig.CATEGORY-BAND",
            "CabrilloConfig.CATEGORY-POWER", "CabrilloConfig.CATEGORY-MODE",
            "CabrilloConfig.CATEGORY-TRANSMITTER", "CabrilloConfig.CATEGORY-ASSISTED",
            "CabrilloConfig.CATEGORY-STATION", "CabrilloConfig.CATEGORY-TIME",
            "CabrilloConfig.CATEGORY-_OVERLAY", "CabrilloConfig.CLAIMED-SCORE",
            "CabrilloConfig.NAME", "CabrilloConfig.ADDRESS", "CabrilloConfig.ADDRESS-CITY",
            "CabrilloConfig.ADDRESS-STATE-PROVINCE", "CabrilloConfig.ADDRESS-POSTALCODE",
            "CabrilloConfig.ADDRESS-COUNTRY", "CabrilloConfig.EMAIL"
        };
        
        for (const auto& key : configKeys) {
            if (cabrilloConfig->hasKey(key)) {
                // 从键名中提取字段名（去掉前缀）
                std::string fieldName = key.substr(std::string("CabrilloConfig.").length());
                outFile << fieldName << ": " << cabrilloConfig->get(key) << "\n";
            }
        }
        
        // 写入QSO记录
        for (const auto& record : records) {
            // CABRILLO格式: QSO: <FREQ> <MODE> <DATE> <TIME> <MYCALL> <MYRST> <MYQTH> <CALL> <RST> <QTH> <EXCHANGE>
            outFile << "QSO: ";
            
            // 频段转换为频率（MHz）
            // std::string freq = UIManager::bandToFrequency(record.band);
            outFile << std::setw(4) << std::left << record.frequency << " ";
            
            // 模式
            outFile << std::setw(3) << std::left << record.mode << " ";
            
            // 日期 (YYYY-MM-DD格式转换为DD/MM/YY)
            // std::string formattedDate = UIManager::formatDateForCabrillo(record.date);
            outFile << record.date << " ";
            
            // 时间 (HHMM格式)
            std::string formattedTime = UIManager::formatTimeForCabrillo(record.time);
            outFile << formattedTime << " ";
            
            // 我的呼号（从配置获取）
            std::string myCall = cabrilloConfig->get("CabrilloConfig.CALLSIGN", "");
            outFile << std::setw(13) << std::left << myCall << " ";
            
            // 我的信号报告
            outFile << std::setw(3) << std::left << record.rst_sent << " ";
            
            // 我的交换信息1
            outFile << std::setw(6) << std::left << record.myexch1 << " ";
            // 我的交换信息2
            outFile << std::setw(6) << std::left << record.myexch2 << " ";
            
            // 对方呼号
            outFile << std::setw(13) << std::left << record.callsign << " ";
            
            // 对方信号报告
            outFile << std::setw(3) << std::left << record.rst_rcvd << " ";
            
            // 对方交换信息1
            outFile << std::setw(6) << std::left << record.exch1 << " ";
            // 对方交换信息2
            outFile << std::setw(6) << std::left << record.exch2 << " ";
            
            // // 交换信息（姓名、QTH等）
            // std::string exchangeInfo = record.name;
            // if (!record.qth.empty()) {
            //     if (!exchangeInfo.empty()) exchangeInfo += " ";
            //     exchangeInfo += record.qth;
            // }
            // outFile << exchangeInfo << "\n";
            outFile << "0" << "\n";
        }
        
        // 写入文件结束标记
        outFile << "END-OF-LOG:\n";
        
        // 关闭文件
        outFile.close();
        
        std::cout << "成功导出 " << records.size() << " 条QSO记录到Cabrillo文件" << std::endl;
        return true;
    } catch (const std::exception& e) {
        std::cerr << "导出Cabrillo日志时发生错误: " << e.what() << std::endl;
        return false;
    }
}

// 辅助函数：将频段转换为频率（MHz）
std::string UIManager::bandToFrequency(const std::string& band) {
    // 简单的频段到频率映射
    if (band == "160") return "1800";
    if (band == "80") return "3500";
    if (band == "40") return "7000";
    if (band == "30") return "10100";
    if (band == "20") return "14000";
    if (band == "17") return "18068";
    if (band == "15") return "21000";
    if (band == "12") return "24890";
    if (band == "10") return "28000";
    if (band == "6") return "50000";
    if (band == "2") return "144000";
    return band; // 如果没有匹配，直接返回原值
}

// 辅助函数：格式化日期为Cabrillo格式 (DD/MM/YY)
std::string UIManager::formatDateForCabrillo(const std::string& date) {
    // 假设输入格式为 YYYY-MM-DD
    if (date.length() >= 10) {
        std::string day = date.substr(8, 2);
        std::string month = date.substr(5, 2);
        std::string year = date.substr(2, 2); // 只取年份的后两位
        return day + "/" + month + "/" + year;
    }
    return date;
}

// 辅助函数：格式化时间为Cabrillo格式 (HHMM)
std::string UIManager::formatTimeForCabrillo(const std::string& time) {
    // 假设输入格式为 HH:MM 或 HH:MM:SS
    if (time.length() >= 5) {
        std::string hour = time.substr(0, 2);
        std::string minute = time.substr(3, 2);
        return hour + minute;
    }
    return time;
}

extern "C" void on_export_ADI_button_clicked(GtkWidget* widget, gpointer data) {
    std::cout << "导出ADI日志按钮被点击" << std::endl;
    
    // 创建文件保存对话框
    GtkWidget *dialog = gtk_file_chooser_dialog_new("保存ADI日志文件",
                                                    nullptr,
                                                    GTK_FILE_CHOOSER_ACTION_SAVE,
                                                    "_取消", GTK_RESPONSE_CANCEL,
                                                    "_保存", GTK_RESPONSE_ACCEPT,
                                                    nullptr);
    
    // 设置默认文件名
    gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), "hamlog.adi");
    
    // 设置文件过滤器
    GtkFileFilter *filter = gtk_file_filter_new();
    gtk_file_filter_set_name(filter, "ADI Files (*.adi)");
    gtk_file_filter_add_pattern(filter, "*.adi");
    gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter);
    
    // 显示对话框
    gint res = gtk_dialog_run(GTK_DIALOG(dialog));
    
    if (res == GTK_RESPONSE_ACCEPT) {
        char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
        std::cout << "选择的文件名: " << filename << std::endl;
        
        // 导出ADI日志
        if (UIManager::export_adi_log(filename)) {
            // 显示成功消息
            GtkWidget *msg_dialog = gtk_message_dialog_new(nullptr,
                                                           GTK_DIALOG_MODAL,
                                                           GTK_MESSAGE_INFO,
                                                           GTK_BUTTONS_OK,
                                                           "ADI日志导出成功！");
            gtk_dialog_run(GTK_DIALOG(msg_dialog));
            gtk_widget_destroy(msg_dialog);
        } else {
            // 显示错误消息
            GtkWidget *msg_dialog = gtk_message_dialog_new(nullptr,
                                                           GTK_DIALOG_MODAL,
                                                           GTK_MESSAGE_ERROR,
                                                           GTK_BUTTONS_OK,
                                                           "ADI日志导出失败！");
            gtk_dialog_run(GTK_DIALOG(msg_dialog));
            gtk_widget_destroy(msg_dialog);
        }
        
        g_free(filename);
    }
    
    gtk_widget_destroy(dialog);
}

// ADI日志导出函数实现
bool UIManager::export_adi_log(const std::string& filename) {
    std::cout << "开始导出ADI日志到文件: " << filename << std::endl;
    
    try {
        // 获取数据库管理器实例
        SQLiteManager& dbManager = SQLiteManager::getInstance();
        
        // 获取所有QSO记录
        std::vector<QSORecord> records = dbManager.getAllQSOs();
        
        // 创建并打开输出文件
        std::ofstream outFile(filename);
        if (!outFile.is_open()) {
            std::cerr << "无法创建或打开文件: " << filename << std::endl;
            return false;
        }
        // 获取当前时间戳 格式为 20251010090000 yyyymmddhhmmss
        std::time_t now = std::time(nullptr);
        char timestamp_buffer[16];
        std::strftime(timestamp_buffer, sizeof(timestamp_buffer), "%Y%m%d%H%M%S", std::localtime(&now));
        std::string created_timestamp = timestamp_buffer;
        
        // 写入ADI文件头部信息
        outFile << "<ADIF_VER:5>3.1.4\n";
        outFile << "<PROGRAM_ID:11>sHamLogX11\n";
        outFile << "<CREATED_TIMESTAMP:14>" << created_timestamp << "\n";
        outFile << "<EOH>\n\n";
        
        // 写入QSO记录
        for (const auto& record : records) {
            // 基本QSO信息
            outFile << "<CALL:" << record.callsign.length() << ">" << record.callsign << "\n";
            // 格式化日期为YYYYMMDD格式
            std::string qso_date = record.date;
            // 移除日期中的分隔符（假设输入格式为 YYYY-MM-DD）
            qso_date.erase(std::remove(qso_date.begin(), qso_date.end(), '-'), qso_date.end());
            outFile << "<QSO_DATE:8>" << qso_date << "\n";
            
            // 格式化时间 HHMMSS格式
            std::string time_on = record.time;
            // 移除时间中的分隔符（假设输入格式为 HH:MM 或 HH:MM:SS）
            time_on.erase(std::remove(time_on.begin(), time_on.end(), ':'), time_on.end());
            // 如果只有4位时间（HHMM），补充为6位（HHMMSS）
            if (time_on.length() == 4) {
                time_on += "00";
            }
            outFile << "<TIME_ON:6>" << time_on << "\n";
            
            // 频段信息
            outFile << "<BAND:" << record.band.length()+1 << ">" << record.band << "m\n";
            
            // 模式
            outFile << "<MODE:" << record.mode.length() << ">" << record.mode << "\n";
            
            float freq = std::stof(record.frequency)/1000;
            // 频率 freq 保留三位小数 
            std::ostringstream oss;
            oss << std::fixed << std::setprecision(3) << freq;
            std::string sFreq = oss.str();
            outFile << "<FREQ:" << sFreq.length()<< ">" << sFreq << "\n";
            
            // 信号报告
            outFile << "<RST_SENT:" << record.rst_sent.length() << ">" << record.rst_sent << "\n";
            outFile << "<RST_RCVD:" << record.rst_rcvd.length() << ">" << record.rst_rcvd << "\n";
            
            // 名称和备注
            if (!record.name.empty()) {
                outFile << "<NAME:" << record.name.length() << ">" << record.name << "\n";
            }
            
            if (!record.memo.empty()) {
                outFile << "<COMMENT:" << record.memo.length() << ">" << record.memo << "\n";
            }
            
            outFile << "<EOR>\n\n";
        }
        
        // 关闭文件
        outFile.close();
        
        std::cout << "成功导出 " << records.size() << " 条QSO记录到ADI文件" << std::endl;
        return true;
    } catch (const std::exception& e) {
        std::cerr << "导出ADI日志时发生错误: " << e.what() << std::endl;
        return false;
    }
}